package com.example.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.*;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class ActivitiController {
    @GetMapping("/test")
    public String test() {
        //1.得到ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //2.得到RunService对象
        RuntimeService runtimeService = processEngine.getRuntimeService();
        //3.创建流程实例(关键步骤)即 启动流程实例
        //需要知道流程定义的Key：holiday（找key的方法  1：bpmn文件中的id，它对应的值就是key
        // 2：直接看数据库中流程定义表act_re_procdet的key值）
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("department");
        //4.输出实例的相关信息
        System.out.println("流程部署ID=" + processInstance.getDeploymentId());//null
        System.out.println("流程定义ID=" + processInstance.getProcessDefinitionId());//holiday:1:4
        System.out.println("流程实例ID=" + processInstance.getId());//2501
        System.out.println("流程活动ID=" + processInstance.getActivityId());//获取当前具体执行的某一个节点的ID(null)

        return "ok";
    }

    @GetMapping("/deploy")
    public String deploy() {
        //1.创建ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

        //2.得到RepositoryService实例
        RepositoryService repositoryService = processEngine.getRepositoryService();

        //3.进行部署
        Deployment deployment = repositoryService.createDeployment()//创建Deployment对象
                .addClasspathResource("processes/department.bpmn20.xml")//添加bpmn文件
                .name("请假申请单流程")
                .deploy();//部署

        //4.输出部署的一些信息
        System.out.println(deployment.getName());
        System.out.println(deployment.getId());
        return "ok";
    }

    @GetMapping("/start")
    public String start(String userId) {
        String msg="";
        //1.得到ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //2.得到RunService对象
        RuntimeService runtimeService = processEngine.getRuntimeService();
        String instanceKey = "department";
        log.info("开启请假流程...");
        Map<String, Object> map = new HashMap<String, Object>();
        //在holiday.bpmn中,填写请假单的任务办理人为动态传入的userId,此处模拟一个id
        map.put("userId", userId);
        ProcessInstance instance = runtimeService.startProcessInstanceByKey(instanceKey, map);
        msg=msg+"启动流程实例成功:"+ instance+"\n"+"流程实例ID:"+instance.getId()+"\n"+"流程定义ID:"+instance.getProcessDefinitionId();
        log.info(msg);
//        log.info("启动流程实例成功:"+ instance);
//        log.info("流程实例ID:"+instance.getId());
//        log.info("流程定义ID:"+instance.getProcessDefinitionId());
        return msg;
    }

    @GetMapping("/apply")
    public String apply(String id,String leaveDays,String leaveReason) {
        String msg="";
        //1.得到ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //2.得到RunService对象
        TaskService taskService = processEngine.getTaskService();
        String instanceId = id; // 任务ID
        Task task = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
        if (task == null) {

            msg+="任务ID"+instanceId+"查询到任务为空！";
            log.info(msg);
            return msg;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("days", leaveDays);
        map.put("date", new Date());
        map.put("reason", leaveReason);
        taskService.complete(task.getId(), map);
        msg+="执行【员工申请】环节，流程推动到【上级审核】环节";
        log.info(msg);
        return msg;
    }

    @GetMapping("/show")
    public String show(String id){
        String msg="";
        //1.得到ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //2.得到RunService对象
        TaskService taskService = processEngine.getTaskService();
        String instanceId = id; // 任务ID

        Task task = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
        String days = (String) taskService.getVariable(task.getId(), "days");
        Date date = (Date) taskService.getVariable(task.getId(), "date");
        String reason = (String) taskService.getVariable(task.getId(), "reason");
        String userId = (String) taskService.getVariable(task.getId(), "userId");
        msg+="请假天数:  " + days+"\n";
        msg+="请假理由:  " + reason+"\n";
        msg+="请假人id:  " + userId+"\n";
        msg+="请假日期:  " + date.toString()+"\n";
        log.info(msg);
        return msg;
    }
    @GetMapping("audit")
    public String audit(String id,String departmentalOpinion){
        String msg="";
        //1.得到ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //2.得到RunService对象
        TaskService taskService = processEngine.getTaskService();
        String instanceId = id; // 任务ID
        Task task = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("departmentalOpinion", departmentalOpinion);
        taskService.complete(task.getId(), map);
        msg+="添加审批意见,请假流程结束";
        log.info(msg);
        return msg;
    }
}
